import { Module } from "vuex"
import { RootState } from "../index"
import { ElMessageBox } from "element-plus"
import http from "@/utils/http"

const state = {
  editMode: "preview" as "preview" | "editable",
  loading: false,
  eidtorRef: null as any,
}

export type EditorState = typeof state

export const store: Module<EditorState, RootState> = {
  namespaced: true,
  state,
  mutations: {
    setEditorRef(state: EditorState, ref: EditorState["eidtorRef"]) {
      state.eidtorRef = ref
    },
    changeMode(state: EditorState, mode: EditorState["editMode"]) {
      state.editMode = mode
    },
    switchLoading(state: EditorState, flag: boolean) {
      state.loading = flag
    },
  },
  actions: {
    // 异步切换文档保存状态
    asyncChangeMode({ commit }) {
      return new Promise((resolve, reject) => {
        ElMessageBox.confirm("当前文档修改后未保存,确定要退出吗", {
          confirmButtonText: "保存文档",
          cancelButtonText: "确认退出",
          distinguishCancelAndClose: true,
          type: "warning",
        })
          .then(() => {
            commit("changeMode", "preview")
            resolve(true)
          })
          .catch((action: string) => {
            if (action === "cancel") {
              commit("changeMode", "preview")
              reject(action)
            }
          })
      })
    },
    // 开始编辑
    async startEdit(
      { commit },
      { fileId, userId, name }: { fileId: number; userId: number; name: string }
    ) {
      const res = await http.post("/edit/startEdit", {
        fileId,
        userId,
        name,
      })
      if (res.code === 1) {
        commit("changeMode", "editable")
      }
    },
    // 停止编辑
    async stopEdit({ commit }, { fileId }: { fileId: number }) {
      const res = await http.post("/edit/stopEdit", {
        fileId,
      })
      if (res.code === 1) {
        commit("changeMode", "preview")
      }
    },
  },
}
